/* Copyright Andy Mitchell 2007. No warranties */

/*
	This allows an object to have 'event handlers' - the means to add arbtriary events, let other objects attach event listeners, and to broadcast that event to listeners.
	It mutates the object that calls it, adding,
		assocObj.addEventHandler(callObj, event, func)
	
	
*/

function EventHandlers_Mutator(assocObj){
	this.eventHandlers = new Object();
	this.assocObj = assocObj;
	
	this.events = new Object();
	
	// Update prototype of assocObj
	this.assocObj.addEventHandler = GIPROTOTYPE.bind( this, this.addEventHandler );	
}


EventHandlers_Mutator.prototype.addEventHandler = function(callObj, eventtype, func){
	// Store this function in a look up table against this event
	// Bind this function up to retain its original context.
	
	var boundFunc = GIPROTOTYPE.bind( callObj, func );	
	if( !this.events[eventtype] ) this.events[eventtype] = new Array();	
	
	this.events[eventtype][ this.events[eventtype].length ] = boundFunc;
};


EventHandlers_Mutator.prototype.broadcast = function(eventtype, eventObj){
	// Call each function in the array for this event type.
	if( !this.events[eventtype] ) return;
	
	var funcArray = this.events[eventtype];
	for( var i = 0; i < funcArray.length; i++ ){
		funcArray[i]( this.assocObj, eventObj );
	}
};

EventHandlers_Mutator.prototype.reset = function(){
	this.events = {};
};

EventHandlers_Mutator.prototype.destroy = function(){
	if( !this.assocObj ) return;
	
	this.assocObj.addEventHandler = null;
	delete this.assocObj.addEventHandler;
	this.assocObj = null;
};